﻿Imports AugmentLib.Database
Imports System.Configuration.ConfigurationManager
Imports AugmentLib.InputOutput.Encryption
Imports AugmentLib.WebComponent
Imports Lsk.Data
Imports Lsk.Business
Imports FlickrNet

Partial Class RecentTransactionEntry
    Inherits System.Web.UI.Page

    Protected Sub BtnSave_Click(sender As Object, e As EventArgs) Handles BtnSave.Click
        'Check if should update or save
        Dim savemode As Boolean = False
        If (lblhidPropertyId.Text = "") Then 'safe mode, new auction
            savemode = True
            Dim alamatExist As Boolean
            alamatExist = CheckDuplicateRecord()
            If (alamatExist) Then
                lblMsgError.Text = "This record already existed in the database. Please update instead of create new one."
                divError.Visible = True
                udpMessage.Update()
                Exit Sub
            End If
        End If

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Try

            objDB.OpenConnection()
            objDB.InitDbTrans()
            objDB.AddParameter("TransactType", Data.SqlDbType.NVarChar, ddlTransactType.SelectedItem.Text)
            objDB.AddParameter("LSK", Data.SqlDbType.TinyInt, ddlLSK.SelectedValue)
            objDB.AddParameter("LandType", Data.SqlDbType.NVarChar, ddlLandType.SelectedItem.Text)
            objDB.AddParameter("PropertyType", Data.SqlDbType.NVarChar, ddlProperyType.SelectedItem.Text) '50
            objDB.AddParameter("Alamat", Data.SqlDbType.NVarChar, txtAlamat.Text)
            objDB.AddParameter("Kawasan", Data.SqlDbType.NVarChar, txtKawasan.Text)
            objDB.AddParameter("Project", Data.SqlDbType.NVarChar, txtProject.Text)
            objDB.AddParameter("Daerah", Data.SqlDbType.NChar, ddlDaerah.SelectedItem.Text)
            objDB.AddParameter("Price", Data.SqlDbType.Decimal, txtPrice.Text)
            objDB.AddParameter("TransactionDate", Data.SqlDbType.Date, Date.ParseExact(txtTransactionDate.Text, "dd-MMM-yyyy", Nothing))
            objDB.AddParameter("Land", Data.SqlDbType.Decimal, txtLand.Text)

            If String.IsNullOrEmpty(txtBuildUp.Text.ToString.Trim()) Then
                objDB.AddParameter("BuildUp", Data.SqlDbType.Decimal, DBNull.Value)
            Else
                objDB.AddParameter("BuildUp", Data.SqlDbType.Decimal, txtBuildUp.Text)
            End If

            If String.IsNullOrEmpty(txtBedroom.Text.ToString.Trim()) Then
                objDB.AddParameter("Bedroom", Data.SqlDbType.Int, DBNull.Value)
            Else
                objDB.AddParameter("Bedroom", Data.SqlDbType.Int, txtBedroom.Text)
            End If
            objDB.AddParameter("CreateWho", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidStaffId.Text))
            objDB.AddParameter("UpdateWho", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidStaffId.Text))

            If (savemode) Then
                objDB.dbVariable.SQLString = "INSERT INTO AW_RecentRentSale (TransactType,LSK,LandType,PropertyType,Alamat,Kawasan,Project,Daerah,Price,TransactionDate,Land,BuildUp,Bedroom,CreatedWho) " & _
                    "VALUES (@TransactType,@LSK,@LandType,@PropertyType,@Alamat,@Kawasan,@Project,@Daerah,@Price,@TransactionDate,@Land,@BuildUp,@Bedroom,@CreateWho)"

            Else
                objDB.AddParameter("TranId", Data.SqlDbType.UniqueIdentifier, New Guid(lblhidPropertyId.Text))
                objDB.dbVariable.SQLString = "UPDATE AW_RecentRentSale SET TransactType=@TransactType,LSK=@LSK,LandType=@LandType,PropertyType=@PropertyType," & _
                    " Alamat=@Alamat,Kawasan=@Kawasan,Project=@Project,Daerah=@Daerah,Price=@Price,TransactionDate=@TransactionDate,Land=@Land,BuildUp=@BuildUp,Bedroom=@Bedroom,UpdateDate=getdate(),UpdateWho=@UpdateWho " & _
                    " WHERE TranId=@TranId"
            End If

            objDB.ExecuteQuery(False)
            objDB.DbTransCommit()
            objDB.CloseConnection()

            'Success, alert success. Clear Textbox
            If (savemode) Then
                lblMsgSuccessful.Text = txtAlamat.Text + " added successfully."
            Else
                lblMsgSuccessful.Text = txtAlamat.Text + " updated successfully."
            End If

            divSuccessful.Visible = True
            udpMessage.Update()
            'ClearForm()

            upPropertyDetail.Update()
        Catch ex As NullReferenceException
            If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                objDB.DbTransRollback()
                objDB.CloseConnection()
            End If
            lblMsgError.Text = ex.Message
            divError.Visible = True
            udpMessage.Update()

        End Try
    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Session("StaffId") Is Nothing Then
            Response.Redirect("Default.aspx")

        Else
            lblhidStaffId.Text = Session("StaffId").ToString
            lblhidStaffType.Text = Session("StaffType").ToString
        End If

        If (lblhidStaffType.Text = "4" Or lblhidStaffType.Text = "6") Then
            Response.Redirect("Dashboard.aspx")
        End If

        If Not Page.IsPostBack Then
            If Not Request.QueryString("id") Is Nothing Then ' Need to load existing auction property
                lblhidPropertyId.Text = Request.QueryString("id") 'SymmetricDecryptFromHex(Request.QueryString("id"), "augment")
                Dim recordExist As Integer = LoadTransaction(lblhidPropertyId.Text)
                If recordExist = 0 Then
                    lblhidPropertyId.Text = "" 'This record basically not exist.
                End If
            End If
        End If
    End Sub

    Protected Function LoadTransaction(TranId As String) As Integer

        'Return 1 if the AuctionID exist, 0 if the property never exist.
        Dim retval = 0

        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable

        objDB.OpenConnection()

        objDB.dbVariable.SQLString = "SELECT TranId,LandType,PropertyType,Alamat,Kawasan,Project,Daerah,Price,TransactionDate" & _
                                    " ,Land,BuildUp,Bedroom,LSK,TransactType" & _
                                    " FROM AW_RecentRentSale where StatusDelete != 1 and TranId = @TranId"
        objDB.AddParameter("@TranId", Data.SqlDbType.UniqueIdentifier, New Guid(TranId))
        objDB.FillData(TempDT, "AW_RecentRentSale", Database.SQLCommandType.NormalString)
        objDB.CloseConnection()

        For Each ReadRow As Data.DataRow In TempDT.Rows

            lblhidPropertyId.Text = ReadRow.Item("TranId").ToString
            If (IsNothing(ddlTransactType.Items.FindByText(ReadRow.Item("TransactType").ToString)) = False) Then
                ddlTransactType.ClearSelection()
                ddlTransactType.Items.FindByText(ReadRow.Item("TransactType").ToString()).Selected = True
            End If

            If (IsNothing(ddlLSK.Items.FindByValue(ReadRow.Item("LSK").ToString)) = False) Then
                ddlLSK.ClearSelection()
                ddlLSK.Items.FindByValue(ReadRow.Item("LSK").ToString()).Selected = True
            End If

            If (IsNothing(ddlLandType.Items.FindByText(ReadRow.Item("LandType").ToString)) = False) Then
                ddlLandType.ClearSelection()
                ddlLandType.Items.FindByText(ReadRow.Item("LandType").ToString()).Selected = True
            End If

            If (IsNothing(ddlProperyType.Items.FindByText(ReadRow.Item("PropertyType").ToString)) = False) Then
                ddlProperyType.ClearSelection()
                ddlProperyType.Items.FindByText(ReadRow.Item("PropertyType").ToString()).Selected = True
            End If

            txtAlamat.Text = ReadRow.Item("Alamat").ToString
            txtKawasan.Text = ReadRow.Item("Kawasan").ToString
            txtProject.Text = ReadRow.Item("Project").ToString

            If (IsNothing(ddlDaerah.Items.FindByText(Trim(ReadRow.Item("Daerah").ToString))) = False) Then
                ddlDaerah.ClearSelection()
                ddlDaerah.Items.FindByText(Trim(ReadRow.Item("Daerah").ToString())).Selected = True
            End If

            txtPrice.Text = ReadRow.Item("Price").ToString
            txtTransactionDate.Text = Format(ReadRow.Item("TransactionDate"), "dd-MMM-yyyy")
            'Date.ParseExact(txtTransactionDate.Text, "dd-MMM-yyyy", Nothing)
            txtLand.Text = ReadRow.Item("Land").ToString
            txtBuildUp.Text = ReadRow.Item("BuildUp").ToString
            txtBedroom.Text = ReadRow.Item("Bedroom").ToString
            retval = 1
        Next
        Return retval
    End Function

    Protected Sub btnUploadPhoto_Click(sender As Object, e As EventArgs) Handles btnUploadPhoto.Click
        Dim url As String

        If Not Request.QueryString("id") Is Nothing Then ' 
            url = "UploadPhoto.aspx?id=" + Request.QueryString("id")
            Response.Redirect(url)

        Else
            lblMsgError.Text = "Please save the entry first!"
            divError.Visible = True
        End If
    End Sub

    Private Function CheckDuplicateRecord() As Boolean
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable
        Try
            objDB.OpenConnection()

            objDB.AddParameter("Alamat", Data.SqlDbType.NVarChar, txtAlamat.Text)
            objDB.AddParameter("TransactionDate", Data.SqlDbType.Date, Date.ParseExact(txtTransactionDate.Text, "dd-MMM-yyyy", Nothing))
            objDB.AddParameter("TransactType", Data.SqlDbType.NVarChar, ddlTransactType.SelectedItem.Text)

            objDB.dbVariable.SQLString = "Select Alamat from AW_RecentRentSale where Alamat = @Alamat and TransactionDate=@TransactionDate and TransactType=@TransactType and StatusDelete != 1"
            objDB.ExecuteQuery(False)
            objDB.FillData(TempDT, "AW_RecentRentSale", Database.SQLCommandType.NormalString)
            objDB.CloseConnection()
            For Each ReadRow As Data.DataRow In TempDT.Rows
                Dim lelongID = ReadRow.Item("Alamat").ToString
                Return True
            Next

        Catch ex As Exception

        End Try

        Return False
    End Function

    Protected Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        Response.Redirect("RecentTransaction.aspx")
    End Sub
End Class
